﻿namespace RevitStarter.Util
{
    using System;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;

    public class UiUtil
    {
        public const string CaptionName = @"Revit启动器";

        /// <summary>
        /// Shows regular message box with information icon and OK button
        /// </summary>
        public static void InformationMessageBox(string message)
        {
            MessageBox.Show(message, CaptionName, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        /// <summary>
        /// Shows regular message box with warning icon and OK button
        /// </summary>
        public static void WarningMessageBox(string message)
        {
            MessageBox.Show(message, CaptionName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }


        /// <summary>
        /// Shows regular message box with warning icon and OK button
        /// </summary>
        public static void ErrorMessageBox(string message)
        {
            MessageBox.Show(message, CaptionName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }


        /// <summary>
        /// 使用倒计时关闭
        /// </summary>
        /// <param name="message"></param>
        /// <param name="interval"></param>
        /// <param name="bLogging"></param>
        public static void ErrorMessageBox2(string message, int interval = 5000, bool bLogging = false)
        {
            var timer = new System.Timers.Timer(interval) {AutoReset = false};
            timer.Elapsed += delegate
            {
                //IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, caption);
                IntPtr mbWnd = FindWindow("#32770", CaptionName); // lpClassName is #32770 for MessageBox
                if (mbWnd != IntPtr.Zero)
                {
                    //SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
                    PostMessage(mbWnd, WM_CLOSE, 0, 0);
                }

                timer.Dispose();
            };

            timer.Enabled = true;
            message += message + string.Format("\n\n*{0}秒将自动关闭此窗口", Math.Ceiling(interval / 1000.0));
            ErrorMessageBox(message);
        }

        /// <summary>
        /// Shows regular message box with warning icon and OK button
        /// </summary>
        public static void FatalMessageBox(string message)
        {
            MessageBox.Show(message, CaptionName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }

        #region 自动关闭的MessageBox

        [DllImport("user32.Dll")]
        static extern int PostMessage(IntPtr hWnd, UInt32 msg, int wParam, int lParam);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

        private const UInt32 WM_CLOSE = 0x0010;

        #endregion
    }
}